#include <stdio.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <expat.h>
#include <string>
#include <fstream>
#include <string.h> 
#include <exception>

#include "IMethod.h"
#include "methodFactory.h"

using std::string;
using std::cout;
using std::cerr;
using std::ifstream;
using std::istreambuf_iterator;
using std::endl;
using std::exception;

void error(string message){
	cerr << message << endl;
	exit(1);
}

int main(int argc, char *argv[]){
		if(argc != 2){
			error(" Usage: ./main filePath");
		}

		try {
			string filePath(argv[1]);
			ifstream input_file;
		   	input_file.open(filePath.c_str());
			if (input_file.fail()){   		
				error("cannot open file");
			}
				
			string fileType = filePath.substr(filePath.find(".") + 1); 
	 		string data ( (istreambuf_iterator<char>(input_file)),
	                      (istreambuf_iterator<char>()) );
			input_file.close();	

			MethodFactory factory;
			IMethod* counter = factory.createMethod(fileType);
			if(counter == NULL){				
				throw "Invalid file type.";
			}
			int count = counter -> run(data);
		
			cout << count << endl;
		}catch (const char* e) {	
			error(e); 			
		}catch (exception e) {			
			error(e.what()); 		
		}catch (...) {			
			error("Error."); 
		}
}
